package com.dejian.bloodPressure;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.igexin.sdk.PushManager;
import com.sam.dialog.LoadingDialog;
import com.sam.gui.activity.RegisterWebActivity;
import com.sam.gui.activity.ResetPwdWebActivity;

import chu.dejian.bloodPressure.R;
import chu.dejian.conf.BLEPreference;
import chu.dejian.models.LoginRequest;
import chu.dejian.models.LoginResponse;
import chu.dejian.restApi.RestClient;
import com.sam.utils.L;
import com.sam.utils.T;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class LoginActivity extends Activity {
	private static final int LOGIN_OUT_TIME = 0;
	private Button mLoginBtn;
	private EditText mAccountEt;
	private EditText mPasswordEt;
	private ConnectionOutTimeProcess mLoginOutTimeProcess;
	private String mAccount;
	private String mPassword;
	private LoadingDialog mLoginDialog;
	private TextView registerBtn,forgetPasswdBtn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		findView();
		initView();
	}

	private void findView(){
		mAccountEt = (EditText) findViewById(R.id.account_input);
		mPasswordEt = (EditText) findViewById(R.id.password);
		mLoginBtn = (Button) findViewById(R.id.login);
		registerBtn = (TextView) findViewById(R.id.register_btn);
		forgetPasswdBtn = (TextView) findViewById(R.id.forget_passwd);
	}
	
	private void initView() {
		String account = BLEPreference.getInstance().getAccount("");
		String password = BLEPreference.getInstance().getPassword("");
		if (!TextUtils.isEmpty(account))
			mAccountEt.setText(account);
		if (!TextUtils.isEmpty(password))
			mPasswordEt.setText(password);

		mAccountEt.addTextChangedListener(textWatcher);
		mLoginBtn.setOnClickListener(onClickListener);
		registerBtn.setOnClickListener(onClickListener);
		forgetPasswdBtn.setOnClickListener(onClickListener);
		final String loginTip = getResources().getString(R.string.logining);
		if(mLoginDialog == null) mLoginDialog = new LoadingDialog(LoginActivity.this,loginTip);
		mLoginOutTimeProcess = new ConnectionOutTimeProcess();
	}
	


	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mLoginOutTimeProcess != null) {
			mLoginOutTimeProcess.stop();
			mLoginOutTimeProcess = null;
		}
	}

	//======================================================================================
	//                 事件定义
	//======================================================================================
	

	private OnClickListener onClickListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.login:
				mLoginBtn.setEnabled(false);
				loginBtnClick();
				break;
			case R.id.register_btn:
				startActivity(new Intent(LoginActivity.this,RegisterWebActivity.class));
				break;
			case R.id.forget_passwd:
				startActivity(new Intent(LoginActivity.this,ResetPwdWebActivity.class));
				break;
			default:
				break;
			}
		}
	};
	
	
	private void loginBtnClick() {
		mAccount = mAccountEt.getText().toString();
		mPassword = mPasswordEt.getText().toString();
		if (TextUtils.isEmpty(mAccount)) {
			T.showShort(this, R.string.null_account_prompt);
			return;
		}
		if (TextUtils.isEmpty(mPassword)) {
			T.showShort(this, R.string.password_input_prompt);
			return;
		}
		if (mLoginOutTimeProcess != null && !mLoginOutTimeProcess.running)
			mLoginOutTimeProcess.start();
		if (mLoginDialog != null && !mLoginDialog.isShowing())
			mLoginDialog.show();
		// 登录 login
		login(mAccount,mPassword);
	}

	private void login(final String user, final String password)
	{
		RestClient.getUnAuthedClient().getApiService().login(new LoginRequest(user, password, 1), new Callback<LoginResponse>() {
			@Override
			public void success(LoginResponse loginResponse, Response response) {
				BLEPreference.getInstance().setPassword(password);
				BLEPreference.getInstance().setToken(loginResponse.getToken());
				BLEPreference.getInstance().setAccount(user);
				PushManager.getInstance().bindAlias(LoginActivity.this,loginResponse.getId()+"");
				RestClient.getUnAuthedClient().setToken(loginResponse.getToken());
				startActivity(new Intent(LoginActivity.this, MainActivity.class));
				mLoginDialog.dismiss();
				finish();
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				mLoginBtn.setEnabled(true);
			}

		});
		mLoginBtn.setEnabled(true);
	}
	
	private TextWatcher textWatcher =  new TextWatcher() {
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			try {
				mLoginBtn.setEnabled(true);
				mAccountEt.setTextColor(getResources().getColor(R.color.main_blue_color));
			} catch (Exception e) {
				mLoginBtn.setEnabled(false);
				mAccountEt.setTextColor(Color.RED);
			}
		}
	};
	
	
	
	//=====================================================================================
	//                      功能函数
	//=====================================================================================
	private void onLoginTimeOut(){
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (mLoginOutTimeProcess != null && mLoginOutTimeProcess.running)
					mLoginOutTimeProcess.stop();
				if (mLoginDialog != null && mLoginDialog.isShowing())
					mLoginDialog.dismiss();
				T.showShort(LoginActivity.this, R.string.timeout_try_again);
			}
		});
	}

	// 登录超时处理线程
	class ConnectionOutTimeProcess implements Runnable {
		public boolean running = false;
		private long startTime = 0L;
		private Thread thread = null;

		ConnectionOutTimeProcess() {
		}

		public void run() {
			while (true) {
				if (!this.running)
					return;
				if (System.currentTimeMillis() - this.startTime > 20 * 1000L) {
					onLoginTimeOut();
				}
				try {
					Thread.sleep(10L);
				} catch (Exception localException) {
					L.e("超时线程启动失败");
				}
			}
		}

		public void start() {
			try {
				this.thread = new Thread(this);
				this.running = true;
				this.startTime = System.currentTimeMillis();
				this.thread.start();
			} finally {
			}
		}

		public void stop() {
			try {
				this.running = false;
				this.thread = null;
				this.startTime = 0L;
			} finally {
			}
		}
	}


//====================================================
//         未使用
//====================================================

	private void logout()
	{
		RestClient.getAuthedClient().getApiService().logout(RestClient.getAuthedClient().getToken(), new Callback() {
			@Override
			public void success(Object o, Response response) {
				BLEPreference.getInstance().setToken("");
			}

			@Override
			public void failure(RetrofitError retrofitError) {
			}
		});
	}

}
